package account

import (
	"content_system/dao/def/account/model"
	"content_system/infra/db"
	"content_system/infra/id_gen"
	"context"
	"errors"
	"gorm.io/gorm"
	"sync"
)

var (
	accountDao     *AccountDao
	accountDaoOnce sync.Once
)

type AccountDao struct{}

func GetAccountDao() *AccountDao {
	accountDaoOnce.Do(func() {
		accountDao = &AccountDao{}
	})
	return accountDao
}

func (d *AccountDao) Create(ctx context.Context, account *model.Account) error {
	table := db.AccountQuery.Account
	if account == nil {
		return errors.New("account is nil")
	}
	if account.ID == 0 {
		id, err := id_gen.Get()
		if err != nil {
			return err
		}
		account.ID = int64(id)
	}
	err := table.WithContext(ctx).Create(account)
	if err != nil {
		return err
	}
	return nil
}

func (d *AccountDao) GetByUsername(ctx context.Context, username string) (*model.Account, error) {
	table := db.AccountQuery.Account
	account, err := table.WithContext(ctx).Where(table.Username.Eq(username)).First()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	return account, nil
}

func (d *AccountDao) GetByUserID(ctx context.Context, uid int64) (*model.Account, error) {
	table := db.AccountQuery.Account
	account, err := table.WithContext(ctx).Where(table.ID.Eq(uid)).First()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	return account, nil
}
